package com.lyc.controller;

import com.lyc.constant.Constant;
import com.lyc.entity.Category;
import com.lyc.entity.Product;
import com.lyc.entity.User;
import com.lyc.entity.biz.UserBiz;
import com.lyc.service.ICategoryService;
import com.lyc.service.ISolrService;
import com.lyc.service.IUserService;
import com.lyc.utils.CollectionUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.InvalidSessionException;
import org.apache.shiro.subject.Subject;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.common.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private IUserService userService;

    @Autowired
    private ICategoryService categoryService;

    @Autowired
    private ISolrService solrService;

    @RequestMapping("/index")
    public String index(Model model) {
        try {
            //生成首页最新/热商品轮播图所需的数据并返回给页面
            List<Product> nList = solrService.getNewProducts();
            List<Product> hList = solrService.getHotProducts();
            List<List<Product>> newList = CollectionUtil.subList(Constant.CAROUSEL_SIZE, nList);
            List<List<Product>> hotList = CollectionUtil.subList(Constant.CAROUSEL_SIZE, hList);
            model.addAttribute("newList", newList);
            model.addAttribute("hotList", hotList);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (SolrServerException e) {
            e.printStackTrace();
        }
        List<Category> categoryList = categoryService.getAll();
        model.addAttribute("categoryList", categoryList);
        return "/user/index";
    }

    @RequestMapping("/checkName")
    @ResponseBody
    public String checkName(String username) {
        if (StringUtils.isEmpty(username))
            return Constant.OPERATE_FAIL;
        User u = userService.checkName(username);
        if (u != null)
            return Constant.OPERATE_FAIL;
        return Constant.OPERATE_SUCCESS;
    }

    @RequestMapping("/register")
    @ResponseBody
    public String register(User user) {
        if (StringUtils.isEmpty(user.getUsername()))
            return Constant.OPERATE_FAIL;
        if (StringUtils.isEmpty(user.getPassword()))
            return Constant.OPERATE_FAIL;
        try {
            userService.register(user);
        } catch (Exception e) {
            e.printStackTrace();
            return Constant.OPERATE_FAIL;
        }
        return Constant.OPERATE_SUCCESS;
    }

    @RequestMapping("/toLogin")
    public String toLogin(HttpServletRequest request,Model model){
        String retUrl = request.getHeader("Referer");//获取上一页请求地址
        if (StringUtils.isEmpty(retUrl))
            retUrl = "/user/index";
        model.addAttribute("backUrl",retUrl);
        return "/common/login";
    }

    /**
     * 2017-08-23 改用shiro提供的md5密码校验器支持加盐功能
     * 弃用自定义的密码校验器，因此之前的几个用户登陆会失败
     * @param biz
     * @param model
     * @return
     */
    @RequestMapping("/login")
    public String login(UserBiz biz,Model model) {
        Subject subject = SecurityUtils.getSubject();
        try {
            boolean isRemember = biz.isRemember();
            if (biz != null) {
                User user = biz.getUser();
                if (user != null) {
                    subject.login(new UsernamePasswordToken(user.getUsername(), user.getPassword(), isRemember));
                    if (SecurityUtils.getSubject().hasRole("admin")){
                        return "redirect:/admin/index";
                    }
                    return "redirect:/user/index";
                }
            }
            //存在cookie
            if (subject.isRemembered()) {
                return "redirect:/user/index";
            }
        } catch (AuthenticationException e) {
            e.printStackTrace();
        } catch (InvalidSessionException e) {
            e.printStackTrace();
        }
        model.addAttribute("content","登录失败");
        model.addAttribute("url","/user/index");
        return "/common/errorModal";
    }

    @RequestMapping("/center")
    public String center() {
        return "/user/user_center";
    }
}
